﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json;

namespace LayuiMvc
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class ToolHelper
    {

        private static JsonSerializerOptions _jsonOption = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
        };
        /// <summary>
        /// 转换json文件内容为对象，文件不存在或异常返回null
        /// </summary>
        /// <param name="file">基于应用程序根目录的相对文件路径</param>
        public static TModel JsonFileToModel<TModel>(string file) where TModel : class, new()
        {
            var path = Path.Combine(AppContext.BaseDirectory, file);
            if (!File.Exists(path))
            {
                return null;
            }

            using var sr = new StreamReader(path);
            try
            {
                var json = sr.ReadToEnd();
                return JsonSerializer.Deserialize<TModel>(json, _jsonOption);
            }
            catch
            {
                return null;
            }
        }
    }
}
